package com.hyperplan.neptune;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class SourceManager {

	public static final String EXTENSION = "nep";
	
	private Map<String, SourceElement> mapping;
	
	public SourceManager() throws Exception {
		mapping = new HashMap<String, SourceElement>();
		for (Path path : Environment.getRootPaths()) {
			loadFile(path.toFile(), path);
		}
	}
	
	private void loadFile(File file, Path root) throws Exception {
		if (file.isDirectory()) {
			for (File child : file.listFiles()) {
				loadFile(child, root);
			}
		} else {
			if (file.getName().endsWith("." + EXTENSION)) {
				Path absPath = Paths.get(file.toURI());
				String relPath = root.relativize(absPath).toString();
				String truncatedPath = relPath.substring(0,
						relPath.length() - EXTENSION.length() - 1);
				List<String> accu = new ArrayList<String>();
				for (Path relPart : Paths.get(truncatedPath)) {
					accu.add(relPart.toString());
				}
				SourceElement element = new SourceElement(
						accu.toArray(new String[] {}), absPath, root);
				if (mapping.containsKey(element.getModuleName())) {
					throw new Exception(String.format(
							"Duplicate module [%s]", element.getModuleName()));
				} else {
					mapping.put(element.getModuleName(), element);
				}
			}
		}
	}
	
	public Map<String, SourceElement> getMapping() {
		return mapping;
	}
}
